<?php

/**
 * cart actions.
 *
 * @package    sf_sandbox
 * @subpackage cart
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class cartActions extends sfActions
{
    /**
     * 
     * updates shipping select tag, when country selected
     */
    public function executeGetshipping()
    {
        $this->number = $this->getRequestParameter('countryId', '');
    }
    public function executeListpdf()
    {
        $c = new Criteria();
        // TODO: Check watch list items
        $c->add(ProductPeer::ID, $this->getUser()->getAttribute('arMyList', array()), Criteria::IN);
        $products = ProductPeer::doSelect($c);
        //debugvar($products);
        $pdf = new pdfList('P', 'pt', 'A4', true, 'UTF-8', false);
        $pdf->prepare($products);
    }
    
    public function executeReceiptpdf()
    {
//        $c = new Criteria();
//        // TODO: Check watch list items
//        $c->add(ProductPeer::ID, $this->getUser()->getAttribute('arMyList', array()), Criteria::IN);
//        $products = ProductPeer::doSelect($c);
        //debugvar($products);
        $id = $this->getRequestParameter('id');
        $receipt = ReceiptPeer::retrieveByPK($id);
        $this->forward404Unless($receipt);
        
        $customer = Customer::getOrCreateByUser($receipt->getUserId());
        $this->forward404Unless($customer);
        $pdf = new pdfCartList('P', 'pt', 'A4', true, 'UTF-8', false);
        $pdf->prepare($receipt, $customer);
    }
    
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
        $this->forward('default', 'module');
    }
    public function executePreview()
    {
        $userId = get_user_id();
        if ($this->getRequestParameter('id'))
        {
            $id = (int)$this->getRequestParameter('id');
            $this->receipt = ReceiptPeer::retrieveByPK($id);
        }else
        {
            if( $userId > 0 )
            {
                $this->receipt = Receipt::getOrCreateByUser($userId);
            }else 
            {
                if(Receipt::isAnonymousCartAllowed())
                {
                    $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
                    if( strlen($uid) < 1 )
                    {
                        $uid = md5(mt_rand());
                        sfContext::getInstance()->getUser()->setAttribute("anonimus_user_uid", $uid);
                    }
                    $this->receipt = Receipt::getOrCreateByAnonymousUid($uid);
                }else
                    $this->redirect('cart/denied');
            }
        }
        $this->forward404Unless($this->receipt);
        $c = new Criteria();
        $c->add(ReceiptItemPeer::RECEIPT_ID, $this->receipt->getId());
        $this->arItems = ReceiptItemPeer::doSelect($c);

        if( $this->receipt->getStatusId() != MyConstants::STATUS_NEW )
        {
            $this->setTemplate('view');
        }
    }
    public function executeDenied()
    {

    }
//    /**
//     * checks if product already added.
//     */
//    public function validateAdd()
//    {
//        $id = (int)$this->getRequestParameter('id', 0);
//        $product = ProductPeer::retrieveByPK($id);
//        if($product)
//        {
//            if( get_user_id() > 0 )
//            {
//                $this->receipt = Receipt::getOrCreateByUser(get_user_id());
//            }else 
//            {
//                $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
//                if( strlen($uid) < 1 )
//                {
//                   $uid = md5(mt_rand());
//                   sfContext::getInstance()->getUser()->setAttribute("anonimus_user_uid", $uid);
//                }
//                $this->receipt = Receipt::getOrCreateByAnonymousUid($uid, true);
//            }
//            $c = new Criteria();
//            $c->add(ReceiptItemPeer::OBJ_ID, $product->getId());
//            $c->add(ReceiptItemPeer::RECEIPT_ID, $this->receipt->getId());
//            $c->setLimit(1);
//            $prod = ReceiptItemPeer::doSelect($c);
//            if(empty($prod))
//            {
//                return true;
//            }else 
//            {
//                $this->getRequest()->setError('id', 'Product already added');
//                return false;
//            }
//        }else 
//        {
//            return false;
//        }
//    }
    public function handleErrorAdd()
    {
        return sfView::SUCCESS;
    }
    public function executeAdd()
    {
        //$this->getResponse()->setStatusCode(404);
        /* @var $product Product */
        $id = (int)$this->getRequestParameter('id', 0);
        $product = ProductPeer::retrieveByPK($id);
        $this->forward404Unless($product);
        $qnt = (int)$this->getRequestParameter('qnt', 1);
        $price = $product->getPrice();
        if( $product->hasTag(Product::PROMO_TAG) )
        {
            $price = $product->getPricePromo();
        }
        $name = $product->getName();
        $userId = get_user_id();
        if( $userId > 0 )
        {
            $this->receipt = Receipt::getOrCreateByUser($userId);
        }else 
        {
            $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
            if( strlen($uid) < 1 )
            {
               $uid = md5(mt_rand());
               sfContext::getInstance()->getUser()->setAttribute("anonimus_user_uid", $uid);
            }
            $this->receipt = Receipt::getOrCreateByAnonymousUid($uid, true);
        }
        if( $this->receipt )
        {
            $receiptItem = new ReceiptItem();
            $receiptItem->setReceiptId($this->receipt->getId());
            $receiptItem->setObjId($id);
            $receiptItem->setQuantity($qnt);
            $receiptItem->setPriceOfItem($price);
            $receiptItem->setName($name);
            $receiptItem->setCurrencyCode($product->getCurrencyCode());
            $receiptItem->save();

            //return $this->renderText(1);
        }

        $this->receipt = ReceiptPeer::retrieveByPK($receiptItem->getReceiptId());
        $this->receipt->setCurrencyCode($receiptItem->getCurrencyCode());
        $this->receipt->save();
        //return $this->renderText(0);
        //$this->forward('cart', 'addandcalc');
    }

    public function executeEmptycart()
    {
        $userId = get_user_id();
        if( $userId > 0 )
        {
            $receipt = Receipt::getOrCreateByUser($userId);
        }else 
        {
            $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
            if( strlen($uid) < 1 )
            {
                $uid = md5(mt_rand());
                sfContext::getInstance()->getUser()->setAttribute("anonimus_user_uid", $uid);
            }
            $receipt = Receipt::getOrCreateByAnonymousUid($uid);
        }
        if( $receipt )
        {
            $c = new Criteria();
            $c->add(ReceiptItemPeer::RECEIPT_ID, $receipt->getId());
            $arReceiptItems = ReceiptItemPeer::doSelect($c);
            foreach($arReceiptItems as $item)
            {
                $item->delete();
            }

        }
        $this->redirect('cart/preview');
    }

    public function executeEdit()
    {
        $receiptItemId = (int)$this->getRequestParameter('id', 0);
        if( $this->getRequestParameter('id', 0) != 0 )
        {
            $c = new Criteria();
            $c->add(ReceiptItemPeer::ID, $receiptItemId);
            $receiptItem = ReceiptItemPeer::doSelectOne($c);
            if( $this->getRequestParameter('price') )
            {
                $price = (int)$this->getRequestParameter('price');
                $receiptItem->setPriceOfItem($price);
            }
            if( $this->getRequestParameter('qnt') )
            {
                $qnt = (int)$this->getRequestParameter('qnt');
                $receiptItem->setQuantity($qnt);
            }

            $receiptItem->save();
        }
        $this->redirect('cart/preview');
    }
    public function executeRemove()
    {
        $receiptItemId = (int)$this->getRequestParameter('id', 0);
        $c = new Criteria();
        $c->add(ReceiptItemPeer::ID, $receiptItemId);
        $receiptItem = ReceiptItemPeer::doSelectOne($c);
        if (!empty($receiptItem))
        {
            $receiptItem->delete();
        }
        $this->redirect('cart/preview');
    }
    public function executeDelete()
    {

    }
    public function executeMylist()
    {
        if( $this->getUser()->hasCredential('Admin') && $this->getUser()->isAuthenticated() == true )
        {
            $this->redirect('cart/list');
        }
        $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
        $c = new Criteria();
        $c->add(ReceiptPeer::UID, $uid);
        $c->addDescendingOrderByColumn(ReceiptPeer::CREATED_AT);
        $this->arReceipts = ReceiptPeer::doSelect($c);

    }
    public function executeList()
    {
        $this->processFilters();
        $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/receipt/filters');
        $this->pager = new sfPropelPager('Receipt', 25);
        $c = new Criteria();
        $this->addFiltersCriteria($c);
        $this->pager->setCriteria($c);
        $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1)));
        $this->pager->init();
        // save page
        if ($this->getRequestParameter('page')) {
            $this->getUser()->setAttribute('page', $this->getRequestParameter('page'));
        }

    }
    protected function processFilters()
    {
        if ($this->getRequest()->hasParameter('filter'))
        {
            $filters = $this->getRequestParameter('filters');

            $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/receipt');
            $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/receipt/filters');
            $this->getUser()->getAttributeHolder()->add($filters, 'sf_admin/receipt/filters');
        }
    }
    protected function addFiltersCriteria($c)
    {
        if (isset($this->filters['user_id']) && $this->filters['user_id'] !== '')
        {
            $c->add(ReceiptPeer::USER_ID, $this->filters['user_id']);
        }
        
        if (isset($this->filters['id']) && $this->filters['id'] !== '')
        {
            $c->add(ReceiptPeer::ID, $this->filters['id']);
        }

        if (isset($this->filters['status']) && $this->filters['status'] !== '')
        {
            $c->add(ReceiptPeer::STATUS_ID, $this->filters['status']);
        }
    }

    public function executeConfirm()
    {
        
        $userId = get_user_id();
        if( $userId > 0 )
        {
            $this->receipt = Receipt::getOrCreateByUser($userId);
            if( $this->getRequestParameter('reset') )
            {
                /* @var $user User */
                $this->customer = new Customer();
                $user = UserPeer::retrieveByPK($userId);
                if($user)
                {
                    $this->customer->setEmail($user->getEmail());
                    $this->customer->setUserId($user->getId());
                }
            }else
            {
                $this->customer = Customer::getOrCreateByUser($this->receipt->getUserId());
                $user = UserPeer::retrieveByPK($this->receipt->getUserId());
                if($user)
                {
                    $this->customer->setEmail($user->getEmail());
                    $this->customer->setUserId($user->getId());
                }
                if( $this->getRequest()->hasErrors() )
                {
                    $this->customer->setReceiptId($this->receipt->getId());
                    $this->customer->setUserId($userId);
                    $this->customer->setStatusId(MyConstants::STATUS_NEW);
                    $this->customer = $this->updateCustomerFromRequest($this->customer);
                }
            }
        }else 
        {
            $uid = sfContext::getInstance()->getUser()->getAttribute("anonimus_user_uid");
            if( strlen($uid) < 1 )
            {
                $uid = md5(mt_rand());
                sfContext::getInstance()->getUser()->setAttribute("anonimus_user_uid", $uid);
            }
            $this->receipt = Receipt::getOrCreateByAnonymousUid($uid);
            $this->forward404Unless($this->receipt);
            if( Receipt::isAnonymousCartAllowed())
            {
                $this->customer = new Customer();
                $this->customer->setReceiptId($this->receipt->getId());
                $this->customer->setStatusId(MyConstants::STATUS_NEW);
                $this->customer = $this->updateCustomerFromRequest($this->customer);
            }
            else 
                $this->redirect('cart/denied');
        }
    }
    protected function updateCustomerFromRequest($customer)
    {
        $customer->setIsCompany($this->getRequestParameter('is_company'));
        $customer->setEmail($this->getRequestParameter('email'));
        $customer->setCountrycode($this->getRequestParameter('countrycode'));
        $customer->setCity($this->getRequestParameter('city'));
        $customer->setZip($this->getRequestParameter('zip'));
        $customer->setStreet($this->getRequestParameter('street'));
        $customer->setName($this->getRequestParameter('name'));
        $customer->setSurname($this->getRequestParameter('surname'));
        $customer->setCompanyName($this->getRequestParameter('company_name'));
        $customer->setCompanyNr($this->getRequestParameter('company_nr'));
        $customer->setFiscalCode($this->getRequestParameter('fiscal_code'));
        $customer->setPhoneNr($this->getRequestParameter('phone'));
        return $customer;
        
    }
    public function executeConfirmform()
    {
        try {
            if( $this->getRequest()->getMethod() == sfRequest::POST )
            {
                
                $this->receipt = ReceiptPeer::retrieveByPK($this->getRequestParameter('receipt'));
                $this->forward404Unless($this->receipt);
                /* @var $shipping Shipping */
                $shipping = ShippingPeer::retrieveByPK($this->getRequestParameter('shipping'));
                if($shipping)
                {
                    $this->receipt->setShippingPrice($shipping->getPrice());
                    $this->receipt->setShippingId($shipping->getId());
                }
                
                /* @var $this->customer Customer */
                $this->customer = new Customer();
                if(get_user_id() > 0)
                {
                    $this->customer->setUserId(get_user_id());
                }
                $this->customer->setReceiptId($this->receipt->getId());
                $this->customer->setStatusId(MyConstants::STATUS_APPROVED);
                $this->customer = $this->updateCustomerFromRequest($this->customer);
                $this->customer->save();
    
                if( false ) //executed when payment per paypalor mokejimai.lt used
                {
                    $form = array();
                    $form['action'] = WebToPay::PAY_URL;
                    $amount = $this->receipt->getTotalPrice($this->getUser()->getAttribute('currency', 'EUR')) 
                            + $this->receipt->getShippingPrice($this->getUser()->getAttribute('currency', 'EUR'));
                    $orderId = md5($this->receipt->getId() 
                                . round($amount) 
                                . $this->customer->getId() 
                                . $this->customer->getUserId());
                    $data = array(
                            'projectid'     => MokejimaiLt::PROJECT_ID,
                            'orderid'       => $orderId,
                            'amount'        => round($amount),
                            'currency'      => $this->getUser()->getAttribute('currency', 'EUR'),
                            'paytext'       => sfContext::getInstance()->getI18N()->__('Products from sansara.lt'),
                            'lang'          => sfContext::getInstance()->getUser()->getCulture() == 'lt'? 'LIT' : 'ENG',
                            'p_firstname'   => $this->customer->getName(),
                            'p_lastname'    => $this->customer->getSurname(),
                            'p_email'       => $this->customer->getEmail(),
                            'sign'          => '300813552e095326d31cdd855b300fbf',
                            'sign_password'          => '300813552e095326d31cdd855b300fbf',
                            'accepturl'     => 'http://eshop.interateitis.lt/test.php/lt/cart/response?answer=accept',
                            'cancelurl'     => 'http://eshop.interateitis.lt/test.php/lt/cart/response?answer=cancel',
                            'callbackurl'   => 'http://eshop.interateitis.lt/test.php/lt/cart/response?answer=callback',
                            'p_street'      => $this->customer->getStreet(),
                            'p_city'        => $this->customer->getCity(),
                            'p_zip'         => $this->customer->getZip(),
                            'p_countrycode' => $this->customer->getCountrycode(),
                            'test'          => 1,
                        );
                    
                    $request = WebToPay::buildRequest($data);
                    
                    $form['data'] = $request;
                    $this->getUser()->setAttribute('orderid', $form['data']['orderid']);
                    // transactionn data loggong db
                    /* @var $transactionData TransactionData */
                    $transactionData = new TransactionData();
                    $transactionData->setStatusId(MyConstants::STATUS_NEW);
                    $transactionData->setStateId(MyConstants::STATUS_NEW);
                    $transactionData->setProjectId($form['data']['projectid']);
                    $transactionData->setReceiptId($this->receipt->getId());
                    $transactionData->setOrderId($form['data']['orderid']);
                    $transactionData->setRequestedAmountCt($form['data']['amount']);
                    $transactionData->setRequestedCurrencyCode($form['data']['currency']);
                    $transactionData->setPaytext($form['data']['paytext']);
                    $transactionData->setCustomerId($this->customer->getId());
                    $transactionData->setUserId($this->receipt->getUserId());
                    $transactionData->setSignPassword($form['data']['sign']);
                    $transactionData->setDataJson(json_encode($form['data']));
                    $transactionData->setIsTest($form['data']['test']);
                    //$transactionData->setIp($this->getRequest()->getRemoteAddress());
                    $transactionData->setIp($_SERVER['REMOTE_ADDR']);
                    $transactionData->save();
                    $this->form = $form;
                    $this->amount = round($this->receipt->getTotalPrice('EUR'));
                    $this->shipping = round($this->receipt->getShippingPrice('EUR'));
                    $this->receipt->setStatusId(MyConstants::STATUS_APPROVED);
                    $this->receipt->save();
                    sfLoader::loadHelpers('Partial');
                    $body = get_partial('cartmailbody'
                                        , array('userId' => $this->receipt->getUserId()
                                            , 'receipt' => $this->receipt
                                            , 'customer' => $this->customer));
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                    $mailTask = new MailTask();
                    $mailTask->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , sfConfig::get('app_webmaster_mail')
                                        , $subject
                                        , $body
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                                        
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                }else 
                {
                    $this->receipt->setStatusId(MyConstants::STATUS_APPROVED);
                    $this->receipt->save();
                    $c = new Criteria();
                    $c->add(ReceiptItemPeer::RECEIPT_ID, $this->receipt->getId());
                    $arProd = ReceiptItemPeer::doSelect($c);
                    sfLoader::loadHelpers('Partial');
                    $message = 'You will be contacted for these goods in order.';
                    $messageSeller = 'Customer have ordered products in sansara.lt store.';
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                    $body = get_partial('cart_info'
                                    , array('cart' => $this->receipt
                                        , 'customer' => $this->customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
                    $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $this->receipt
                                                , 'customer' => $this->customer
                                                , 'message' => $messageSeller));
                    $mailTask = new MailTask();
                    //mail for customer
                    $mailTask->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , $this->customer->getEmail()
                                        , $subject
                                        , $body
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                    //mail for seller
                    $mailTaskSeller = new MailTask();
                    $mailTaskSeller->createNew(get_user_id()
                                            , MailTask::PRIORITY_HIGH
                                            , $subject
                                            , sfConfig::get('app_webmaster_mail')
                                            , $subject
                                            , $bodySeller
                                            , sfConfig::get('app_webmaster_mail')
                                            , sfConfig::get('app_webmaster_mail'));
                    $this->arProducts = $arProd;
                    $this->redirect('cart/confirmed');
                }
            }
            
            $this->setTemplate('confirmSuccess');
        }
        catch (WebToPayException $e) {
            $_SESSION['error'] = $e->getMessage();
            $this->message = $e->getMessage();
        }
            
    }
    public function executeConfirmed()
    {
        $this->setTemplate('confirmSuccess');
    }
    public function handleErrorConfirmForm()
    {
        $this->forward('cart', 'confirm');
    }
    
    public function executeOrders()
    {
        $this->processFilters();
        $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/receipt');
        $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/receipt/filters');
        $this->pager = new sfPropelPager('Receipt', 25);
        $c = new Criteria();
        $c->addDescendingOrderByColumn(ReceiptPeer::CREATED_AT);
        $c->add(ReceiptPeer::STATUS_ID, array(MyConstants::STATUS_APPROVED, MyConstants::STATUS_PAID_PENDING_INFO), Criteria::IN);
        $this->pager->setCriteria($c);
        $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1)));
        $this->pager->init();
        // save page
        if ($this->getRequestParameter('page')) 
        {
            $this->getUser()->setAttribute('page', $this->getRequestParameter('page'));
        }
    }
    public function executePerform()
    {
        $receipt = ReceiptPeer::retrieveByPK($this->getRequestParameter('id'));
        if( $receipt )
        {
            $receipt->setStatusId(MyConstants::STATUS_COMPLETED);
            $receipt->setCompletedAt(time());
            $receipt->save();
        }
        $this->redirect('cart/orders');
    }
    public function executeUserinfo()
    {
        $cart = $this->getRequestParameter('cart', 0);
        $c = new Criteria();
        $c->add(CustomerPeer::RECEIPT_ID, $cart);
        $customer = CustomerPeer::doSelectOne($c);
        if($customer)
            $this->customer = $customer;
        else 
            $this->customer = new Customer();
        $c = new Criteria();
        $c->add(CountriesPeer::ISO_3166_NUMERIC, $this->customer->getCountrycode());
        $this->country = CountriesPeer::doSelectOne($c);
        $this->setLayout('empty');
    }
    
    //-------------------------------------------payment------------------------------------------------------//
    /**
     * 
     * post request data to mokejimai.lt and get response
     */
    public function executeResponse()
    {
        $response = $this->getRequestParameter('answer', 'cancel');
        switch ($response) {
            case 'callback':
                $this->executeCallback();
                //$this->message = 'Info about payment';
            break;
            case 'accept':
                $this->executeAccept();
            break;
            case 'paypal':
                $this->executeAcceptpaypal();
            break;
            default:
                $this->executeCancel();
            break;
        }
    }
    /**
     * handling callback info
     */
    public function executeCallback()
    {
        try
        {
            echo 'OK';
            
            $data = new TransactionData();
            $da = json_encode($_GET);
            $data->setDataJson($da);
            $data->save();
            
            $response = WebToPay::getPrefixed($_GET, WebToPay::PREFIX);
            $c = new Criteria();
            $c->add(TransactionDataPeer::ORDER_ID, $response['orderid']);
            $transactionData = TransactionDataPeer::doSelectOne($c);
            // check transaction state
            if(!$transactionData)
            {
                throw new Exception('Missing requested data.');
            }
            if($transactionData->getStateId() == MyConstants::STATE_COMPLETED)
            {
                throw new Exception('This cart already paid.');
            }
            if($transactionData->getStateId() == MyConstants::STATE_FAILED)
            {
                throw new Exception('This cart payment was failed.');
            }
            if($transactionData->getStateId() == MyConstants::STATE_PAYMENT_REJECTED)
            {
                throw new Exception('This cart payment was rejected.');
            }
            $this->receipt = ReceiptPeer::retrieveByPK($transactionData->getReceiptId());
            if(!$this->receipt)
            {
                throw new Exception('Cart for this payment not found.');
            }
            $request = json_decode($transactionData->getDataJson(), true);
            
            //check version, ss2, projectid, sign_password
//            WebToPay::checkResponse($_GET
//                                , array('projectid'     => $request['projectid'],
//                                        'orderid'       => $request['orderid'],
//                                        'amount'        => $request['amount'],
//                                        'currency'      => $request['currency'],
//                                        'sign_password' => '300813552e095326d31cdd855b300fbf',
//                                        'sign' => $request['sign'],));
            $transactionData->setReturnedStatus($response['status']);
            $transactionData->setReturnedSs2($response['_ss2']);
            if(isset($response['error']))
            {
                $transactionData->setReturnedError($response['error']);
            }
            $transactionData->setPaidAmountCt($response['payamount']);
            $transactionData->setPaidCurrencyCode($response['paycurrency']);
            $transactionData->setStateId(MyConstants::STATE_APPROVED);
            $transactionData->setStatusId(MyConstants::STATUS_APPROVED);
            //$transactionData->setApprovedAt($meta['time']);
            $transactionData->save();
            $customer = CustomerPeer::retrieveByPK($transactionData->getCustomerId());
            if(!$customer)
            {
                throw new Exception('Error: customer info not found');
            }
            /* @var $customer Customer */
            //check state
            sfLoader::loadHelpers('Partial');
            if ($response['status'] == MokejimaiLt::RESPONSE_STATUS_SUCCESS)
            {
                $transactionData->setPaidAmountCt($response['payamount']);
                $transactionData->setPaidCurrencyCode($response['paycurrency']);
                if($transactionData->checkAmountCyrrency())
                {
                    $transactionData->setStateId(MyConstants::STATE_COMPLETED);
                    $transactionData->setStatusId(MyConstants::STATUS_COMPLETED);
                    $transactionData->save();
                    $this->receipt->setStatusId(MyConstants::STATUS_COMPLETED);
                    $this->receipt->save();
                }else 
                {
                    $this->receipt->setStatusId(MyConstants::STATUS_FALSE_AMOUNT);
                    $this->receipt->save();
                    throw new Exception('Paid false amount.');
                }
                
                
                    //mailing
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                    $c = new Criteria();
                    $c->add(ReceiptItemPeer::RECEIPT_ID, $transactionData->getReceiptId());
                    $arProd = ReceiptItemPeer::doSelect($c);
                    
                    $message = 'Payment was successful.';
                    $body = get_partial('cart_info'
                                    , array('cart' => $this->receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
                    $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $this->receipt
                                                , 'customer' => $customer
                                                , 'message' => $message));
                    $mailTask = new MailTask();
                    //mail for customer
                    $mailTask->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , $customer->getEmail()
                                        , $subject
                                        , $body
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                    //mail for seller
                    $mailTaskSeller = new MailTask();
                    $mailTaskSeller->createNew(get_user_id()
                                            , MailTask::PRIORITY_HIGH
                                            , $subject
                                            , sfConfig::get('app_webmaster_mail')
                                            , $subject
                                            , $bodySeller
                                            , sfConfig::get('app_webmaster_mail')
                                            , sfConfig::get('app_webmaster_mail'));
            } else 
            {
                if ($response['status'] == MokejimaiLt::RESPONSE_STATUS_FAILED)
                {
                    $transactionData->setStateId(MyConstants::STATE_FAILED);
                    $transactionData->setStatusId(MyConstants::STATUS_FAILED);
                    $this->receipt->setStatusId(MyConstants::STATUS_FAILED);
                    //letter for user and seller
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                    $c = new Criteria();
                    $c->add(ReceiptItemPeer::RECEIPT_ID, $transactionData->getReceiptId());
                    $arProd = ReceiptItemPeer::doSelect($c);
                    
                    $message = 'Payment error. This order will be NOT delivered.';
                    $body = get_partial('cart_info'
                                    , array('cart' => $this->receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
                    $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $this->receipt
                                                , 'customer' => $customer
                                                , 'message' => $message));
                    $mailTask = new MailTask();
                    //mail for customer
                    $mailTask->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , $customer->getEmail()
                                        , $subject
                                        , $body
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                    //mail for seller
                    $mailTaskSeller = new MailTask();
                    $mailTaskSeller->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , sfConfig::get('app_webmaster_mail')
                                        , $subject
                                        , $bodySeller
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                                        
                }elseif ($response['status'] == MokejimaiLt::RESPONSE_STATUS_OUTSTANDING )
                {
                    $transactionData->setStateId(MyConstants::STATE_PENDING_PAYMENT);
                    $transactionData->setStatusId(MyConstants::STATUS_PENDING_PAYMENT);
                    $this->receipt->setStatusId(MyConstants::STATUS_PENDING_PAYMENT);
                    //letter for seller
                    $message = 'Payment info. Payment order is accepted, but still unsettled.';
                    $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
                    $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $this->receipt
                                                , 'customer' => $customer
                                                , 'message' => $message));
                    $mailTask = new MailTask();
                    $mailTask->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , sfConfig::get('app_webmaster_mail')
                                        , $subject
                                        , $bodySeller
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
                }
            }
            $transactionData->save();
            $this->receipt->save();
            echo 'OK';
            
        }catch (Exception $e)
        {
            $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
            $message = 'Payment error. One order will be NOT delivered. ' . $e->getMessage();
            $bodySeller = $message . ' Pleace check carts list. ';
                    //mail for seller
                    $mailTaskSeller = new MailTask();
                    $mailTaskSeller->createNew(get_user_id()
                                        , MailTask::PRIORITY_HIGH
                                        , $subject
                                        , sfConfig::get('app_webmaster_mail')
                                        , $subject
                                        , $bodySeller
                                        , sfConfig::get('app_webmaster_mail')
                                        , sfConfig::get('app_webmaster_mail'));
            
            $this->message = $e->getMessage();
        }
    }
    /**
     * actions when payment canceled
     */
    public function executeCancel()
    {
        try 
        {
            $orderid = $this->getUser()->getAttribute('orderid', 0);
            $c = new Criteria();
            $c->add(TransactionDataPeer::ORDER_ID, $orderid);
            $data = TransactionDataPeer::doSelectOne($c);
            /* @var $data TransactionData */
            if(!$data)
            {
                throw new Exception('Error: missing data');
            }
            if($data->getStateId() != MyConstants::STATE_NEW)
            {
                throw new Exception('Error: order handled allready');
            }
            $receiptId = $data->getReceiptId();
            $receipt = ReceiptPeer::retrieveByPK($receiptId);
            if(!$receipt)
            {
                $data->setStateId(MyConstants::STATE_FAILED);
                $data->setStatusId(MyConstants::STATUS_FAILED);
                $data->save();
                throw new Exception('Error: cart not found');
            }
            $data->setStateId(MyConstants::STATE_PAYMENT_REJECTED);
            $data->setStatusId(MyConstants::STATUS_PAYMENT_REJECTED);
            $data->save();
            $receipt->setStatusId(MyConstants::STATUS_PAYMENT_REJECTED);
            $receipt->save();
            $this->message = 'Payment was rejected';
            echo 'OK';
        }
        catch (Exception $e)
        {
            $this->message = $e->getMessage();
        }
        
    }
    /**
     * actions when payment accept
     */
    public function executeAccept()
    {
        try {
            $orderid = $this->getUser()->getAttribute('orderid', 0);
            $c = new Criteria();
            $c->add(TransactionDataPeer::ORDER_ID, $orderid);
            $data = TransactionDataPeer::doSelectOne($c);
            /* @var $data TransactionData */
            if(!$data)
            {
                throw new Exception('Error: missing data');
            }
            if($data->getStateId() != MyConstants::STATE_NEW)
            {
                throw new Exception('Error: order accepted allready');
            }
            $receiptId = $data->getReceiptId();
            $receipt = ReceiptPeer::retrieveByPK($receiptId);
            if(!$receipt)
            {
                $data->setStateId(MyConstants::STATE_FAILED);
                $data->setStatusId(MyConstants::STATUS_FAILED);
                $data->save();
                throw new Exception('Error: cart not found');
            }
            /* @var $receipt Receipt */
            $data->setStatusId(MyConstants::STATUS_PAID_PENDING_INFO);
            $data->setStateId(MyConstants::STATE_PENDING_PAYMENT);
            $data->save();
            $receipt->setStatusId(MyConstants::STATUS_PAID_PENDING_INFO);
            $receipt->save();
            $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
            $customer = CustomerPeer::retrieveByPK($data->getCustomerId());
            if(!$customer)
            {
                throw new Exception('Error: customer info not found');
            }
            /* @var $customer Customer */
            $c = new Criteria();
            $c->add(ReceiptItemPeer::RECEIPT_ID, $data->getReceiptId());
            $arProd = ReceiptItemPeer::doSelect($c);
            $message = 'You have paid for products in vintageboutique.lt store.
                        When we get more info about payment, you will by informed.';
            sfLoader::loadHelpers('Partial');
            $body = get_partial('cart_info'
                                    , array('cart' => $receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
            $mailTask = new MailTask();
            $mailTask->createNew(get_user_id()
                                , MailTask::PRIORITY_HIGH
                                , $subject
                                , $customer->getEmail()
                                , $subject
                                , $body
                                , sfConfig::get('app_webmaster_mail')
                                , sfConfig::get('app_webmaster_mail'));
            $messageSeller = 'Customer have paid for products in vintageboutique.lt store.
                        When we get more info about payment, you will by informed.';
            $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $receipt
                                                , 'customer' => $customer
                                                , 'message' => $messageSeller));
            $mailTaskSeller = new MailTask();
            $mailTaskSeller->createNew(get_user_id()
                                , MailTask::PRIORITY_HIGH
                                , $subject
                                , sfConfig::get('app_webmaster_mail')
                                , $subject
                                , $bodySeller
                                , sfConfig::get('app_webmaster_mail')
                                , sfConfig::get('app_webmaster_mail'));
            $this->message = get_partial('cart_info'
                                    , array('cart' => $receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
        }
        catch (Exception $e)
        {
            $this->message = $e->getMessage();
            $this->setTemplate('response');
        }
    } 
    
    public function executeAcceptpaypal()
    {
        try {
            $tx = $orderid = $this->getRequestParameter('tx', 0);
            $orderid = $this->getRequestParameter('item_number', 0);
            $c = new Criteria();
            $c->add(TransactionDataPeer::ORDER_ID, $orderid);
            $data = TransactionDataPeer::doSelectOne($c);
            /* @var $data TransactionData */
            if(!$data)
            {
                throw new Exception('Error: missing data');
            }
            if($data->getStateId() != MyConstants::STATE_NEW)
            {
                throw new Exception('Error: order accepted allready');
            }
            $data->setProject('PayPal');
            $data->setTransactionId($tx);
            $data->setSignPassword('');
            $data->setProjectId('');
            $data->save();
            $receiptId = $data->getReceiptId();
            $receipt = ReceiptPeer::retrieveByPK($receiptId);
            if(!$receipt)
            {
                $data->setStateId(MyConstants::STATE_FAILED);
                $data->setStatusId(MyConstants::STATUS_FAILED);
                $data->save();
                throw new Exception('Error: cart not found');
            }
            /* @var $receipt Receipt */
            $str = self::getPostedAnsver('https://www.sandbox.paypal.com/cgi-bin/webscr'
                                        , 'cmd=_notify-synch&tx=39618574V3887682N&at=50ILOpqdcn7_pWMRbNWxrGh1oqd2Kbq-seHbAvVzl2hdpWHmKTHWoXS-MpW');
            $ar = array();
            $arStrings = preg_split('/\n/', $str);
            foreach($arStrings as $string)
            {
                $value = split('=', $string);
                if(empty($value[1]))
                {
                    $ar[$value[0]] = $value[0];
                }else 
                {
                    $ar[$value[0]] = $value[1];
                }
            }
            $data->setDataJson(json_encode($ar));
            $data->save();
            if(isset($ar['FAIL']))
            {
                $data->setReturnedStatus($ar['FAIL']);
                $data->setStateId(MyConstants::STATE_FAILED);
                $data->setStatusId(MyConstants::STATUS_FAILED);
                $data->save();
                $receipt->setStatusId(MyConstants::STATUS_FAILED);
                $receipt->save();
                throw new Exception('Error: Payment fail.');
            }
            if(isset($ar['SUCCESS']))
            {
                $data->setReturnedStatus($ar['SUCCESS']);
                $data->setPaidAmountCt($ar['mc_gross']*100);
                $data->setPaidCurrencyCode($ar['mc_currency']);
                if($data->checkAmountCyrrency())
                {
                    $data->setStatusId(MyConstants::STATUS_COMPLETED);
                    $data->setStateId(MyConstants::STATE_COMPLETED);
                    $data->save();
                    $receipt->setStatusId(MyConstants::STATUS_COMPLETED);
                    $receipt->save();
                }else
                {
                    $receipt->setStatusId(MyConstants::STATUS_FALSE_AMOUNT);
                    $receipt->save();
                }
            }
            
            $subject = sfContext::getInstance()->getI18N()->__(sfConfig::get('app_website_payment_info'));
            $customer = CustomerPeer::retrieveByPK($data->getCustomerId());
            if(!$customer)
            {
                throw new Exception('Error: customer info not found');
            }
            /* @var $customer Customer */
            $c = new Criteria();
            $c->add(ReceiptItemPeer::RECEIPT_ID, $data->getReceiptId());
            $arProd = ReceiptItemPeer::doSelect($c);
            $message = 'You have paid for products in vintageboutique.lt store.';
            sfLoader::loadHelpers('Partial');
            $body = get_partial('cart_info'
                                    , array('cart' => $receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
            $mailTask = new MailTask();
            $mailTask->createNew(get_user_id()
                                , MailTask::PRIORITY_HIGH
                                , $subject
                                , $customer->getEmail()
                                , $subject
                                , $body
                                , sfConfig::get('app_webmaster_mail')
                                , sfConfig::get('app_webmaster_mail'));
            $messageSeller = 'Customer have paid for products in vintageboutique.lt store (PayPal).';
            $bodySeller = get_partial('cart_info_seller'
                                            , array('cart' => $receipt
                                                , 'customer' => $customer
                                                , 'message' => $messageSeller));
            $mailTaskSeller = new MailTask();
            $mailTaskSeller->createNew(get_user_id()
                                , MailTask::PRIORITY_HIGH
                                , $subject
                                , sfConfig::get('app_webmaster_mail')
                                , $subject
                                , $bodySeller
                                , sfConfig::get('app_webmaster_mail')
                                , sfConfig::get('app_webmaster_mail'));
            $this->message = get_partial('cart_info'
                                    , array('cart' => $receipt
                                        , 'customer' => $customer
                                        , 'arProducts' => $arProd
                                        , 'message' => $message));
        }
        catch (Exception $e)
        {
            $this->message = $e->getMessage();
            $this->setTemplate('response');
        }
    }
/**
* Returns data from server
*
* @param $url string full URL where to POST data (i.e. http://www.example.com/test/post)
* @param $data string data to be sent (i.e. id=2&q=abc)
* @return string response from server
*/
    public function getPostedAnsver($url, $data)
    {
        $str = '';
        $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $url );
            @curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            // set post method
            @curl_setopt ( $ch, CURLOPT_POST, 1 );
            @curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
            // load and get page
            $str = curl_exec ( $ch );
            // close connection
            curl_close ( $ch );
            return $str;
    }
    public function executeJson()
    {
        $str = '';
        $data = json_decode('{"answer":"callback","wp_projectid":"11320","wp_orderid":"3e927068fc891162e28590655c97c27a","wp_lang":"lit","wp_amount":"80","wp_currency":"EUR","wp_paytext":"U\u017esakymas nr: 3e927068fc891162e28590655c97c27a http:\/\/eshop.interateitis.lt\/ projekte. (Pardav\u0117jas: Vidute Juodvalkiene) (11320)","wp_p_firstname":"Varvene Pavardene","wp_p_lastname":"pavarde","wp_p_email":"it@interateitis.lt","wp_p_street":"street 12345654321","wp_p_city":"asdsasd","wp_p_zip":"asdads","wp_p_countrycode":"LT","wp_test":"1","wp_version":"1.3","wp_type":"EMA","wp_payment":"hanza","wp_country":"LT","wp_m_pay_restored":"15074758","wp_p_countryname":"Lietuva","wp_receiverid":"164920","wp__ss1":"a6fd71c4e598c2d0d68f7e969fd4a424","wp_status":"1","wp_name":"","wp_surename":"","wp_payamount":"80","wp_paycurrency":"EUR","wp__ss2":"op8lN\/BMT\/b6pEYnQ7TfAZ4GZZjsTibKYxQHSP+y0fBe+E8luUSdLghhyCvj8MIBdWMbFKKeJR1dLH9\/NYwD3aWXdUYSS7v7z7VtQbeg8ODx6Oh1nvj8oMUYAlEx\/MC08S+bnd3zxy7M+zW4bCXiK79cEwqANNHM\/HAB9OeVpa4="}', true);
        foreach ($data as $value => $dat)
        {
            $str = $str . '&' . $value . '=' . $dat;
        }
        debugvar($str, 'string');
        exit('json');
    }
    
    //webmaster_mail-------------------------------------------END payment------------------------------------------------------//
/**
* Returns POSTed data from server
*
* @param $url string full URL where to POST data (i.e. http://www.example.com:8080/test/post)
* @param $data string data to be sent (i.e. id=2&q=abc)
* @return string response from server
*/
    function GetPostedData($url, $data)
    {
        $result = "";
    
        // Extracting data from URL
        $arUrl = parse_url($url);
        debugvar($arUrl, "Posting to:");
    
        // Preparing POST header
        $header = sprintf("
            POST %s HTTP/1.0\r\nContent-type: application/x-www-form-urlencoded\r\nHost: %s\r\nContent-length: %d\r\nConnection: close\r\n\r\n"
            , $arUrl["path"]
            , $arUrl["host"]
            , strlen($data)
            );
        
    
        $fp = fsockopen($arUrl["host"], $arUrl["port"], &$errno, &$errstr, 30);
        if( $fp )
        {
            debugvar("POSTing header: " . $header);
            // Sending header and data
            fputs($fp, $header);
            debugvar("POSTing data: " . $data);
            fputs($fp, $data . "\r\n\r\n");
    
            // Get response from server
            while( !feof($fp) )
            {
                $result .= fgets($fp, 1024);
            }
            fclose($fp);
        }else
        {
            throw new Exception($errstr . "[" . $errno . "]");
        }
    
        return $result;
    }
    

}